const TOKEN_KEY = 'auth_token';

function getToken() {
  try {
    const tokenData = wx.getStorageSync(TOKEN_KEY);
    if (!tokenData) return null;
    
    const currentTime = Date.now();
    if (currentTime > tokenData.expireTime) {
      console.log('Token 已过期');
      wx.removeStorageSync(TOKEN_KEY);
      return null;
    }
    
    return tokenData;
  } catch (e) {
    console.error('获取 Token 失败：', e);
    return null;
  }
}

function request(options) {
  const token = getToken();
  const defaultOptions = {
    method: 'GET',
    header: {
      'Content-Type': 'application/json'
    }
  };
  if (token) {
    defaultOptions.header[token.tokenName] = token.tokenValue;
  }
  const finalOptions = { ...defaultOptions, ...options };
  return new Promise((resolve, reject) => {
    wx.request({
      ...finalOptions,
      success(res) {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          console.log('Token 无效，需重新登录');
          //wx.navigateTo({ url: '/pages/login/login' });
          //reject(new Error('未授权'));
        } else {
          reject(res);
        }
      },
      fail(err) {
        console.error('请求失败：', err);
        reject(err);
      }
    });
  });
}

function saveToken(tokenName, tokenValue) {
  try {
    const expireTime = Date.now() + 24 * 60 * 60 * 1000; //一天后过期
    wx.setStorageSync(TOKEN_KEY, {
      tokenName,
      tokenValue,
      expireTime
    });
    console.log('Token 保存成功');
  } catch (e) {
    console.error('保存 Token 失败：', e);
  }
}
function clearToken() {
  try {
    wx.removeStorageSync(TOKEN_KEY);
    console.log('Token 已清除');
  } catch (e) {
    console.error('清除 Token 失败：', e);
  }
}

export default {
  request,
  saveToken,
  clearToken,
  getToken
};